package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: ngsapitask-cdcs
 * @package: com.elite.groovy.callback
 * @className: apiDynLogin
 * @author: LiJT
 * @description: 外部系统打开手机动态页面Main
 * @date: 2023-05-05 20:17
 * @version: 1.0
 */

public class apiDynLogin implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiDynLogin.class);

    private static String out_DOMAIN = "";
    private static String in_DOMAIN = "";
    private static JdbcTemplate jt = null;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 调用Method过滤
        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        if (getMethod != "GET") {
            errorRedirect(response, "页面异常", "HTTP请求调用类型错误，接口调用失败：" + getMethod);
        }

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParams = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParams.put(key, value);

        }

        // 获取调用数据
        String Syncpram = request.getQueryString();
        log.info("接收调用GET参数信息：" + Syncpram);

        // 初始化参数
        out_DOMAIN = KHUtil.isNull(out_DOMAIN) ? KHDBConfig.getAPIURL(eliteBean, "SYS-OuterDomain") : out_DOMAIN;
        out_DOMAIN = out_DOMAIN.endsWith("/") ? out_DOMAIN : out_DOMAIN + "/";

        in_DOMAIN = KHUtil.isNull(in_DOMAIN) ? KHDBConfig.getAPIURL(eliteBean, "SYS-InnerDomain") : in_DOMAIN;
        in_DOMAIN = in_DOMAIN.endsWith("/") ? in_DOMAIN : in_DOMAIN + "/";

        // 获取数据源List<Map<String, Object>>
        jt = new JdbcTemplate(eliteBean.getDataSource());

        // 获取嵌入传递的参数
        /* opsource
        1 德高官网
        2 德高微信公众号
        4 天润语音平台
        5 勤策365
        6 乐购乐销

        3 西卡BFM企业微信
        */
        String opsource = request.getParameter("opsource");// 第三方系统来源渠道

        // 根据类型识别处理逻辑 通过minip小程序 wxc公众号登录是客户
        if (opsource == "1" || opsource == "2" || opsource == "4" || opsource == "5" || opsource == "6") {
            dealCustLogin(eliteBean, response, mapParams, opsource);
        } else if (opsource == "3") {
            dealStaffLogin(eliteBean, response, mapParams, opsource);
        } else {
            errorRedirect(response, "", "页面走丢了(来源渠道信息异常)");
        }

    }

    // 客户登录处理
    public static void dealCustLogin(EliteBean eliteBean, HttpServletResponse response, Map<String, String> mapParams, String opsource) {

        // 解析登录信息
        String dynid = GetMapV(mapParams, "dynid");// 业务类型
        String service = GetMapV(mapParams, "service");// 打开工单页参数根据不同业务类型区分:异常反馈：FW_FWYC 无标签产品查询：FW_WBQ
        String dept_id = GetMapV(mapParams, "dept_id");// 第三方系统当前登录人登录部门ID,为空则默认客服系统默认组
        String user_id = GetMapV(mapParams, "user_id");// 第三方系统当前登录人身份ID,如操作员ID 操作员登录名或Token ,如果是Token需要提供基于Token获取对应人员身份信息的API接口
        String woid = GetMapV(mapParams, "woid");// woid 业务数据主键
        String taskid = GetMapV(mapParams, "taskid");// taskid 业务数据次主键
        String expand = GetMapV(mapParams, "expand");// 拓展参数,通常用于后期增加的参数可以是字符串或json对象,但需要UrlEncode编码

        String userid = "";
        String usertype = "";

        // 通过minip小程序 wxc公众号登录是客户
        if (!KHUtil.isNull(dynid)) {
            // 预定义返回用户信息

            if (!KHUtil.isNull(service)) {

                // 客服系统是否存在客户信息
                String checkSQL = "Select Customer_Guid As Userid, 'customer' As Usertype, Mobile From Customer Where Customer_Id = ? Order By Createddate Desc Limit 1";
                List<Map<String, Object>> selectExits = jt.queryForList(checkSQL, user_id);
                log.debug("检查当前客服系统是否存在客户信息是否有效-结果:" + selectExits.toString());

                if (selectExits.size() > 0) {
                    Map selectExitsm = selectExits.get(0);
                    userid = selectExitsm.get("Userid");
                    usertype = selectExitsm.get("Usertype");

                } else {

                    try {
                        // TODO 此处可以查询乐购乐销或其他第三方系统客户,并维护到Customer

                        userid = user_id;
                        usertype = "notype";

                    } catch (Exception e1) {
                        log.error("接口处理异常", e1);
                        errorRedirect(response, "页面异常", "接口处理异常");

                    }
                }

            } else {
                errorRedirect(response, "页面异常", "未获取到业务类型信息：业务类型不能为空");
            }

            log.debug("获取当前登录人在系统中的信息:" + userid + "/" + usertype);

            //获取NGS菜单短码
            String apiLinkJson = Util.doHttpGet(in_DOMAIN + "groovy/GeneralService/apiShortenLink?dynid=" + dynid + "&userid=" + userid + "&usertype=" + usertype + "&woid=" + woid + "&taskid=" + taskid + "&expand=" + expand + "&cbtype=&opsource=" + opsource, "UTF-8", 5000, 0);
            JSONObject reLinkJson = JSONObject.fromObject(apiLinkJson);
            log.debug("获取的短链接地址:" + reLinkJson.toString());
            String linkURL = KHUtil.GetSFJV(reLinkJson, "message");

            response.sendRedirect(linkURL);

        } else {
            errorRedirect(response, "页面异常", "登录信息dynid异常：");
        }
    }

    // 员工登录处理
    public static void dealStaffLogin(EliteBean eliteBean, HttpServletResponse response, Map<String, String> mapParams, String opsource) {

        // 解析登录信息
        String dynid = GetMapV(mapParams, "dynid");// 业务类型
        String service = GetMapV(mapParams, "service");// 打开工单页参数根据不同业务类型区分:异常反馈：FW_FWYC 无标签产品查询：FW_WBQ
        String dept_id = GetMapV(mapParams, "dept_id");// 第三方系统当前登录人登录部门ID,为空则默认客服系统默认组
        String user_id = GetMapV(mapParams, "user_id");// 第三方系统当前登录人身份ID,如操作员ID 操作员登录名或Token ,如果是Token需要提供基于Token获取对应人员身份信息的API接口
        String woid = GetMapV(mapParams, "woid");// woid 业务数据主键
        String taskid = GetMapV(mapParams, "taskid");// taskid 业务数据次主键
        String expand = GetMapV(mapParams, "expand");// 拓展参数,通常用于后期增加的参数可以是字符串或json对象,但需要UrlEncode编码

        String userid = "";
        String usertype = "";

        // 通过minip小程序 wxc公众号登录是客户
        if (!KHUtil.isNull(dynid)) {
            // 预定义返回用户信息

            if (!KHUtil.isNull(user_id)) {

                // 检查当前登录用户在系统中是否有效(人&组&关系)
                String checkSQL = "Select Staff_Id, Loginname, 'staff' As Usertype, 1 As Sno From Staff Where Qw_Id = ? Order By Sno Limit 1";
                List<Map<String, Object>> checkSQLList = jt.queryForList(checkSQL, user_id);
                log.debug("检查当前登录用户在系统中是否有效-结果:" + checkSQLList.toString());

                if (checkSQLList.size() > 0) {
                    Map checkSQLMap = checkSQLList.get(0);
                    userid = checkSQLMap.get("Staff_Id");
                    usertype = checkSQLMap.get("Usertype");

                } else {

                    try {
                        // TODO 此处可以查询乐购乐销或其他第三方系统客户,并维护到Customer

                        userid = user_id;
                        usertype = "notype";

                    } catch (Exception e1) {
                        log.error("接口处理异常", e1);
                        errorRedirect(response, "页面异常", "接口处理异常");

                    }
                }

            } else {
                errorRedirect(response, "页面异常", "未获取到认证信息：user_id不能为空");
            }

            log.debug("获取当前登录人在系统中的信息:" + userid + "/" + usertype);

            //获取NGS菜单短码
            String apiLinkJson = Util.doHttpGet(in_DOMAIN + "groovy/GeneralService/apiShortenLink?dynid=" + dynid + "&userid=" + userid + "&usertype=" + usertype + "&woid=" + woid + "&taskid=&expand=" + expand + "&cbtype=&opsource=" + opsource, "UTF-8", 5000, 0);
            JSONObject reLinkJson = JSONObject.fromObject(apiLinkJson);
            log.debug("获取的短链接地址:" + reLinkJson.toString());

            String linkURL = KHUtil.GetSFJV(reLinkJson, "message");

            response.sendRedirect(linkURL);

        } else {
            errorRedirect(response, "页面异常", "登录信息dynid异常：");
        }
    }

    // 异常&错误重定向
    public static void errorRedirect(HttpServletResponse response, String ErrorTitle, String ErrorInfo) {
        log.warn("异常&错误[apiDynLogin]重定向 ErrorTitle:" + ErrorTitle + " ErrorInfo:" + ErrorInfo);
        ErrorTitle = KHUtil.isNull(ErrorTitle) ? "页面异常" : ErrorTitle;
        ErrorInfo = KHUtil.isNull(ErrorInfo) ? "请稍后再试或联系管理员." : ErrorInfo;
        response.sendRedirect(out_DOMAIN + "ngs/404.html?ErrorTitle=" + URLEncoder.encode(ErrorTitle, "UTF-8") + "&ErrorInfo=" + URLEncoder.encode("登录异常&错误:" + ErrorInfo, "UTF-8").replaceAll("\\+", "%20"));
    }

    // 解析Mapn值(此方法增加需要解析的key不存在保护)
    public static String GetMapV(Map inMap, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = String.valueOf(inMap.get(getKey));
        } catch (Exception e) {

            Rev_Value = "";
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }
}